#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymongo
import pandas as pd
import numpy as np
from config import *
import pyecharts as pc
import matplotlib.pyplot as plot
client=pymongo.MongoClient(MONGO_URL);
import tushare
import jieba
db=client["stock"]
plot.style.use('ggplot')
plot.rcParams['font.sans-serif'] = ['SimHei']
plot.rcParams['font.family']='sans-serif'
"https://blog.csdn.net/stevenkwong/article/details/52528616"


def get_data(TABLE):
    queryArgs = {}
    projectionFields = {'_id': False}  # 用字典指定
    result = db[TABLE].find(queryArgs,projectionFields)
    return result

def get_tags(words):
    result={}
    all_word=[]
    for word in words:
        for i in jieba.cut(word):
            all_word.append(i)
    for all in all_word:
        if result.get(all) ==None:
            result[all]=1
        else:
            result[all]+=1
    return result


def get_stocks(data):
    result={}
    stocks=list(data["cube_stocks"])
    for stock in stocks:
        for ss  in stock:
            if result.get(ss)== None:
                result[ss]=1
            else:
                result[ss]+=1

    return result



def main():
    data1=pd.DataFrame(list(get_data("2018424")))
    data2 = pd.DataFrame(list(get_data("2018425")))
    data3=pd.DataFrame(list(get_data("2018426")))

    data=pd.concat([data1,data2,data3],axis=0)

    data.drop_duplicates(["cube_author"],keep="last")
    data["cube_rate"]=data2["cube_rate"].astype(np.float)
    data["cube_follwer"]=data["cube_follwer"].astype(np.float)
    data=data.sort_values(by="cube_follwer",ascending=True)
    print(data.head())
    stock_cube_in(data)




def tags_hangye(data):
    tags = list(data["cube_tags"])
    tags_result = get_tags(tags)
    word_cluds = pc.WordCloud(width=1300, height=620)
    word_cluds.add("组合股票所属行业", list(tags_result.keys()), list(tags_result.values()), word_size_range=[20, 80])
    word_cluds.render()


def stock_cube_in(data):
    stocks=get_stocks(data)
    stocks=sorted(stocks.items(),key = lambda x:x[1],reverse = True)
    stocks=dict(stocks)
    stocks=pd.DataFrame(list(stocks.values()),index=list(stocks.keys()),columns=["count"])
    print(stocks.tail(len(data)-10))
    stocks = stocks.head(20)
    bar = pc.Bar(width=2042,height=600)
    bar.add("股票入选组合的个数", stocks.index, stocks["count"], xaxis_rotate=30)
    bar.render()


def cube_rate_follwer(data):
    line = pc.Line()
    line.add("组合关注人数与收益率关系", data["cube_follwer"], data["cube_rate"], mark_point=["max"])
    line.render()


def cube_rate(data):
    plot.hist(data["cube_rate"], bins=10, color='red', normed=False)
    plot.title("组合收益率分布")
    plot.xlabel("组合收益率(%)")
    plot.ylabel("个数")
    plot.savefig("cube_rate.png")
    plot.show()


if __name__ == '__main__':
    main()

   # data=tushare.get_hist_data("600276",start='2017-04-25',end='2018-04-25')
   # data=data.sort_index(ascending=True)
   #
   # #[open, close, lowest, highest]
   # data_list = []
   # for dates, row in data.iterrows():
   #
   #      # 将时间转换为数字
   #      open, high, close, low = row[:4]
   #      datas = ( open, high, low, close)
   #      data_list.append(datas)
   # kline=pc.Kline("恒瑞医药最近一年股价走势图")
   # kline.add("",data.index,data_list)
   # kline.render()
   #
   # print(data.head())